<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]" v-show="showSearch">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="110px" label-suffix=":">
            <el-form-item label="操作员账号" prop="userName">
              <el-input v-model="queryParams.userName" placeholder="请输入操作员账号" clearable style="width: 240px" />
            </el-form-item>
            <el-form-item label="操作员姓名" prop="nickName">
              <el-input v-model="queryParams.nickName" placeholder="请输入操作员姓名" clearable style="width: 240px" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable style="width: 240px" />
            </el-form-item>
            <el-form-item label="所属企业" prop="unitName">
              <el-input v-model="queryParams.unitName" placeholder="请输入所属企业" clearable style="width: 240px" />
            </el-form-item>
            <el-form-item label="所属企业编号" prop="unitNo">
              <el-input v-model="queryParams.unitNo" placeholder="请输入所属企业编号" clearable style="width: 240px" />
            </el-form-item>
            <el-form-item label="角色" prop="roleId">
              <el-select v-model="queryParams.roleId" placeholder="角色" clearable style="width: 240px">
                <el-option v-for="dict in plat_role" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 240px">
                <el-option v-for="dict in oprator_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery" icon="Search" v-hasPermi="['system:user:listNew']">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" plain @click="handleAdd()" icon="Plus" v-hasPermi="['system:user:addNew']">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table ref="roleTableRef" v-loading="tableloading" :data="operList" border>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作员账号" align="center" prop="userName" width="130" />
        <el-table-column label="操作员姓名" align="center" prop="nickName" :show-overflow-tooltip="true" width="150" />
        <el-table-column label="手机号码" align="center" prop="phonenumber" :show-overflow-tooltip="true" width="200" />
        <el-table-column label="所属企业" align="center" prop="unitName" width="220" />
        <el-table-column label="所属企业编号" align="center" prop="unitNo" width="200" />
        <el-table-column label="角色" align="center" prop="roleId" width="100">
          <template #default="scope">
            <dict-tag :options="plat_role" :value="scope.row.roleId" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="confirmEvent(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" v-hasPermi="['system:user:editNew']" @click="mdyOper(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="分配权限" placement="top">
              <el-button link type="primary" icon="CircleCheck" v-hasPermi="['system:user:cfgPer']" @click="perDrawer(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="修改密码" placement="top">
              <el-button link type="primary" @click="mdyPwd(scope.row)" icon="Key" v-hasPermi="['system:user:resetPwdNew']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <el-drawer v-model="drawer.show" :title="drawer.title" size="36%">
      <div style="width:95%;margin:auto;">
        <el-form ref="userRef" :model="form" :rules="rules" label-width="100px" label-suffix=":">
          <el-form-item label="操作员姓名" prop="nickName">
            <el-input v-model="form.nickName" placeholder="请输入操作员姓名" />
          </el-form-item>
          <el-form-item label="操作员账号" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入操作员账号" :disabled="form.userNameDis" />
          </el-form-item>
          <el-form-item label="登录密码" prop="password" v-if="!form.hidePwd">
            <el-input v-model="form.password" placeholder="请输入登录密码" type="password" show-password />
          </el-form-item>
          <el-form-item label="确认密码" prop="repwd" v-if="!form.hidePwd">
            <el-input v-model="form.repwd" placeholder="请输入确认密码" type="password" show-password />
          </el-form-item>
          <el-form-item label="联系邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入联系邮箱" />
          </el-form-item>
          <el-form-item label="手机号" prop="phonenumber">
            <el-input v-model="form.phonenumber" placeholder="请输入手机号" />
            <el-alert title="请务必准确填写手机号，用于登录验证或用于短信接收。" type="error" show-icon :closable="false" />
          </el-form-item>
          <div style="width:100%;margin:auto;text-align:center">
            <el-button type="danger" @click="closeDrawer">取消</el-button>
            <el-button type="primary" @click="submit" :loading="loading">保存并关闭</el-button>
          </div>
        </el-form>
      </div>
    </el-drawer>

    <el-drawer v-model="drawerPer.show" :title="drawerPer.title" size="36%">
      <div style="width:95%;margin:auto;">
        <el-form ref="drawerPerRef" :model="form" :rules="rules" label-width="100px" label-suffix=":">
          <el-form-item label="功能权限" prop="nickName">
            <el-tree
              :data="menuOptions"
              show-checkbox
              ref="menuRef"
              node-key="id"
              :check-strictly="!menuCheckStrictly"
              empty-text="加载中，请稍候"
              :props="{ label: 'label', children: 'children' }"
            ></el-tree>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div style="display:flex;flex-direction:row;justify-content:space-between;">
          <el-dropdown @command="handleCommand">
            <el-button type="primary">
              树操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="1">父子关联</el-dropdown-item>
                <el-dropdown-item command="2">取消关联</el-dropdown-item>
                <el-dropdown-item command="3">全部勾选</el-dropdown-item>
                <el-dropdown-item command="4">取消全选</el-dropdown-item>
                <el-dropdown-item command="5">展开所有</el-dropdown-item>
                <el-dropdown-item command="6">合并所有</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <div style="text-align:right;width:50%;">
            <el-button type="danger" @click="closePerDrawer">取消</el-button>
            <el-button type="primary" @click="submitPre" :loading="loading">保存并关闭</el-button>
          </div>
        </div>
      </template>
    </el-drawer>
    <!-- 修改密码 -->
    <el-dialog :title="dialog.title" v-model="openMdyPwd" width="500px" append-to-body>
      <el-form :model="mdyForm" :rules="mdyRules" ref="pwdRef" label-width="100px" label-suffix=":">
        <el-form-item label="操作员账号" prop="userName">
          <el-input v-model="mdyForm.userName" :disabled="true" />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="mdyForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="repwd">
          <el-input v-model="mdyForm.repwd" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="mdyLoading" @click="mdySubmit">确 定</el-button>
          <el-button @click="cancelMdyPwd">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {addOper,listOper,resetPwdNew,updNew,changeSt,userMenuTreeselect,configUserPer} from "@/api/system/operater";
import { addRole, changeRoleStatus, dataScope, delRole, getRole, listRole, updateRole, deptTreeSelect } from "@/api/system/role";
import { roleMenuTreeselect, treeselect as menuTreeselect } from '@/api/system/menu/index';
import { RoleVO, RoleForm, RoleQuery, DeptTreeOption } from '@/api/system/role/types';
import { MenuTreeOption, RoleMenuTree } from '@/api/system/menu/types';


 const router = useRouter();
 const { proxy } = getCurrentInstance() as ComponentInternalInstance;
 const { plat_role } = toRefs<any>(proxy?.useDict('plat_role'));
 const { oprator_status } = toRefs<any>(proxy?.useDict('oprator_status'));



 const userRef  = ref<ElFormInstance>();
 const queryFormRef = ref<ElFormInstance>();
 const pwdRef = ref<ElFormInstance>();
 const menuRef = ref<ElTreeInstance>();
 const roleList = ref<RoleVO[]>();
 const loading = ref(false)
 const mdyLoading = ref(false)
 const tableloading = ref(false)
 const showSearch = ref(true)
 const ids = ref<Array<string | number>>([])
 const single = ref(true)
 const multiple = ref(true)
 const total = ref(0)
 const menuOptions = ref([])
 const menuExpand = ref(false)
 const menuNodeAll = ref(false)
 const deptExpand = ref(true)
 const deptNodeAll = ref(false)
 const deptOptions = ref<DeptTreeOption[]>([])
 const openMdyPwd = ref(false)
 const operList = ref([])
 const formPre = ref({
    userId:null,
    menuIds:[]
 })
const drawer = ref({
  title:"新增",
  show:false
})

//
const drawerPer = ref({
    show:false,
    title:'权限分配'
});


const dialog = ref({
  visible: false,
  title: ''
});


const form = ref({
  userId:null,
  hidePwd:false,
  userNameDis:false,
  status: '0',
  userName: '',
  nickName: '',
  email: '',
  phonenumber: '',
  password: '',
  repwd: '',
  status: '0'
});


const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  userName: '',
  nickName: '',
  phonenumber: '',
  unitName:'',
  unitNo:'',
  roleId:null,
  status:null
});


const mdyForm = ref({
  userId :null,
  userName:'',
  password:"",
  repwd:""
});

const menuCheckStrictly = ref(true)


const equalToPassword = (rule: any, value: string, callback: any) => {
  if (form.value.password !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const equalToPasswordMdy = (rule: any, value: string, callback: any) => {
  if (mdyForm.value.password !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};



const rules = ref({
    userName: [{ required: true, message: "操作员账号不能为空", trigger: "blur" }],
    nickName: [{ required: true, message: "操作员姓名不能为空", trigger: "blur" }],
    password: [{ required: true, message: "登录密码不能为空", trigger: "blur" }],
    repwd: [{ required: true, message: "确认密码不能为空", trigger: "blur" },{required: true, validator: equalToPassword, trigger: "blur" }],
    email: [{ required: true, message: "Email不能为空", trigger: "blur" }],
    phonenumber: [{ required: true, message: "手机号不能为空", trigger: "blur" }]
})


const mdyRules = ref({
    password: [{ required: true, message: "新密码不能为空", trigger: "blur" }],
    repwd: [{ required: true, message: "确认密码不能为空", trigger: "blur" },{required: true, validator: equalToPasswordMdy, trigger: "blur" }]
})

const str2Int =(v:string)=>{
  return parseInt(v);
}
/** 提交按钮 */
const submit = () => {
  userRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try{
        loading.value = true;
        if(!form.value.userId){
           let result =  await addOper(form.value);
           getList();
           form.value = {
              userId:null,
              hidePwd:false,
              userNameDis:false,
              status: '0',
              userName: '',
              nickName: '',
              email: '',
              phonenumber: '',
              password: '',
              repwd: '',
              status: '0'
            }
           proxy?.$modal.msgSuccess("添加成功");
           drawer.value.show = false;

        }else{
           let result =  await updNew(form.value);
           proxy?.$modal.msgSuccess("修改成功");
        }
        loading.value = false;

      }catch(e){
        loading.value = false;
      }
    }
  });
};



/** 修改密码保存按钮 */
const mdySubmit = () => {
  pwdRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try{
        mdyLoading.value = true;
        let result =  await resetPwdNew(mdyForm.value);
        mdyLoading.value = false;
        proxy?.$modal.msgSuccess("修改成功");
      }catch(e){
        mdyLoading.value = false;
      }
    }
  });
};

 const handleAdd = ()=>{
  form.value = {
              userId:null,
              hidePwd:false,
              userNameDis:false,
              status: '0',
              userName: '',
              nickName: '',
              email: '',
              phonenumber: '',
              password: '',
              repwd: '',
              status: '0'
            }
  drawer.value.title = "新增";
  drawer.value.show  = true;
 }

 const closeDrawer = ()=>{
   drawer.value.show  = false;
 }

const closePerDrawer =()=>{
    drawerPer.value.show = false;
}
/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}


/** 重置 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}



/**
 * 查询角色列表
 */
const getList = () => {
  tableloading.value = true
  listOper(queryParams.value).then(res => {
    operList.value = res.rows
    total.value = res.total
    tableloading.value = false
  })
}

const mdyPwd = (row)=>{
  dialog.value.visible = true;
  openMdyPwd.value = true;
  mdyForm.value.userId = row.userId;
  mdyForm.value.userName = row.userName;
  dialog.value.title = row.userName+" 修改密码";
}

//编辑
const mdyOper = (row)=>{
  form.value.userId = row.userId;
  form.value.userNameDis = true;
  form.value.hidePwd = true;
  form.value.userName = row.userName;
  form.value.nickName = row.nickName;
  form.value.email = row.email;
  form.value.phonenumber = row.phonenumber;
  drawer.value.title = row.userName+ "修改";
  drawer.value.show  = true;
}


const cancelMdyPwd  =()=>{
  openMdyPwd.value = false;

}


const confirmEvent = async(row) => {
  let userId  = row.userId;
  let status = row.status ;
  let result =  await changeSt({userId:userId,status:status});
  proxy?.$modal.msgSuccess("操作成功");
  getList();

}


const getMenuTreeselect = async(uid)=>{
    let result =  await userMenuTreeselect(uid);
    menuOptions.value = result.data.menus;
    result.data.checkedKeys.forEach((v) => {
      nextTick(() => {
        menuRef.value?.setChecked(v, true, false);
      })
    })
}


//权限
const perDrawer = (row)=>{
  drawerPer.value.show = true;
  formPre.value.userId = row.userId;
  getMenuTreeselect(row.userId);
}


const handleCommand = (command:number) => {
  if(command == 5){
      let treeList = menuOptions.value;
      for (let i = 0; i < treeList.length; i++) {
        if (menuRef.value) {
          menuRef.value.store.nodesMap[treeList[i].id].expanded = true;
        }
      }
  }else if(command == 6){
      let treeList = menuOptions.value;
      for (let i = 0; i < treeList.length; i++) {
        if (menuRef.value) {
          menuRef.value.store.nodesMap[treeList[i].id].expanded = false;
        }
      }
  }else if(command == 3){
     menuRef.value?.setCheckedNodes(menuOptions.value);
  }else if(command == 4){
     menuRef.value?.setCheckedNodes([]);
  }else if(command == 2){
    menuCheckStrictly.value = false;
  }else if(command == 1){
    menuCheckStrictly.value = true;
  }

}


/** 所有菜单节点数据 */
const getMenuAllCheckedKeys = (): any => {
  // 目前被选中的菜单节点
  let checkedKeys = menuRef.value?.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = menuRef.value?.getHalfCheckedKeys();
  if (halfCheckedKeys) {
    checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys);
  }
  return checkedKeys;
}



//分配权限
const submitPre = async()=>{
  try{
    loading.value = true;
    let menuId = getMenuAllCheckedKeys();
    formPre.value.menuIds = menuId;
    let result = await configUserPer(formPre.value);
    proxy?.$modal.msgSuccess("操作成功");
    drawerPer.value.show = false;

    loading.value = false;
  }catch(e){
    loading.value = false;
  }
}
onMounted(() => {
  getList();
});
</script>

<style>

.el-alert {
  margin: 5px 0 0;
}

.el-drawer__header{
  border-bottom: 1px solid #e8e8e8;
  padding-bottom:15px;
}

.el-dialog__header{
  border-bottom: 1px solid #e8e8e8;
  padding-bottom:15px;
  margin-right:0;
}

.el-drawer__footer{
   border-top: 1px solid #e8e8e8;
}
</style>
